package com.wxg.spring.boot.blog.v1.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.wxg.spring.boot.blog.v1.domain.UserV1;
import com.wxg.spring.boot.blog.v1.repository.UserRepositoryV1;

/**
 * CreateTime: 2018年10月29日 上午10:56:40
 *
 * @author wxg
 */
@RestController
@RequestMapping("/usersV1")
public class UserControllerV1 {

    @Autowired
    private UserRepositoryV1 userRepository;

    @GetMapping
    public ModelAndView list(Model model) {
        model.addAttribute("userList", userRepository.listUsers());
        model.addAttribute("title", "用户管理");
        return new ModelAndView("v1/users/list", "userModel", model);
    }

    @GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") Long id, Model model) {
        UserV1 user = userRepository.getUserById(id);
        model.addAttribute("user", user);
        model.addAttribute("title", "查看用户");
        return new ModelAndView("v1/users/view", "userModel", model);
    }

    /**
     * 获取表单页面
     * CreateTime: 2018年10月29日 上午11:06:55
     *
     * @param model
     * @return
     * @author wxg
     */
    @GetMapping("/form")
    public ModelAndView createForm(Model model) {
        model.addAttribute("user", new UserV1());
        model.addAttribute("title", "创建用户");
        return new ModelAndView("v1/users/form", "userModel", model);
    }

    @PostMapping
    public ModelAndView create(UserV1 user) {
        user = userRepository.saveOrUpdateUser(user);
        return new ModelAndView("redirect:/usersV1");
    }

    @GetMapping(value = "delete/{id}")
    public ModelAndView delete(@PathVariable("id") Long id, Model model) {
        userRepository.deleteUser(id);

        model.addAttribute("userList", userRepository.listUsers());
        model.addAttribute("title", "删除用户");
        return new ModelAndView("v1/users/list", "userModel", model);
    }

    @GetMapping(value = "modify/{id}")
    public ModelAndView modifyForm(@PathVariable("id") Long id, Model model) {
        UserV1 user = userRepository.getUserById(id);

        model.addAttribute("user", user);
        model.addAttribute("title", "修改用户");
        return new ModelAndView("v1/users/form", "userModel", model);
    }
}
